package com.banciyuan.bcywebview.biz.main.group.talk;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.GroupWork;
import de.greenrobot.daoexample.model.TagDetail;

public class GroupTalkFragment extends BaseLazyContainerFragment {
    private RequestQueue queue;
    private String name;
    private String id;
    private String type;

    private List<GroupWork> glist = new ArrayList<>();
    private PullToRefreashRecycleView mRefreash;
    private RecyclerView recyclerView;

    private int page = 1;
    private boolean loading = false;
    private boolean end_flag = false;

    private GroupTalkAdapter mGroupTalkAdapter;
    private ProgressbarHelper mProgressbarHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.refresh_recycle_layout, container, false);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initProgressbar(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    protected void initProgressbar(View rootview) {
        View mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    loading = true;
                    mProgressbarHelper.onLoading();
                    end_flag = false;
                    page = 1;
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initAction() {
        mRefreash.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                if (!loading) {
                    loading = true;
                    end_flag = false;
                    page = 1;
                    initData();
                }
            }
        });
        recyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!loading && !end_flag) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
        Bundle args = getArguments();
        if (!TextUtils.isEmpty(args.getString("name"))) {
            name = args.getString("name");
        }
        if (!TextUtils.isEmpty(args.getString("id"))) {
            id = args.getString("id");
        }
        if (!TextUtils.isEmpty(args.getString("type"))) {
            type = args.getString("type");
        }
    }

    @Override
    protected void initUi(View rootview) {
        mRefreash = (PullToRefreashRecycleView) rootview.findViewById(R.id.listView);
        recyclerView = mRefreash.getRefreshableView();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

    @Override
    protected void initData() {
        String url = "";
        if (type.equals(HttpUtils.WORK)) {
            url = HttpUtils.BASE_URL + GroupApi.getListhotcore();
        } else if (type.equals(HttpUtils.TAG)) {
            url = HttpUtils.BASE_URL + TagApi.getDetail();
        }
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.ID, id));
        paramsList.add(new BcyPair(HttpUtils.NAME, name));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        paramsList.add(new BcyPair(HttpUtils.TAG_FILTER, "group"));
        Map<String, String> map = HttpUtils.getData(paramsList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {

                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject outerData = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        String data = outerData.getString("group_data");
                        List<GroupWork> tempList = gson.fromJson(data, new TypeToken<List<GroupWork>>() {
                        }.getType());
                        setWorkToTag(tempList);
                        renderGroup(tempList);
                        onSucc();
                    } else {
                        onError();
                    }
                } catch (Exception e) {
                    onError();
                }
            }
        };

        final Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private void onError() {
        loading = false;
        mRefreash.onRefreshComplete();
        mProgressbarHelper.onFailed();
    }

    private void setWorkToTag(List<GroupWork> templist) {
        for (GroupWork groupWork : templist) {
            if (!TextUtils.isEmpty(groupWork.getWork())) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setType("work");
                tagDetail.setWork(groupWork.getWork());
                tagDetail.setWid(groupWork.getWid());
                tagDetail.setTag_name(groupWork.getWork());
                groupWork.getTags().add(0, tagDetail);
            }
        }
    }

    private void renderGroup(List<GroupWork> templist) {
        if (page == 1) {
            glist.clear();
        }
        if (templist.isEmpty()) {
            end_flag = true;
        } else {
            if (templist.get(templist.size() - 1).is_end()) {
                end_flag = true;
            }
        }
        glist.addAll(templist);
        if (mGroupTalkAdapter == null) {
            mGroupTalkAdapter = new GroupTalkAdapter(glist, getActivity());
            recyclerView.setAdapter(mGroupTalkAdapter);
        } else {
            mGroupTalkAdapter.notifyDataSetChanged();
        }
    }

    private void onSucc() {
        loading = false;
        mRefreash.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }

    @Override
    public void selfUpdateData() {
        if (null != mRefreash && null != recyclerView) {
            recyclerView.scrollToPosition(0);
            mRefreash.setRefreshing();
        }
    }

}
